package com.dingreading.cloud.admin.util.bean;

import com.dingreading.cloud.admin.entity.Books;
import com.dingreading.cloud.admin.entity.StoreBooks;
import com.dingreading.cloud.admin.service.BooksService;
import com.dingreading.cloud.admin.service.StoreBooksService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.AliyunBookDto;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.aliyun.AliyunBookUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class BookImportUtil {

    @Resource
    BooksService booksService;
    @Resource
    StoreBooksService storeBooksService;


    /**
     * 异步批量插入总部书籍，阿里云查询
     */
    @Async
    public void insertBook(List<Books> newList, Map<String, Integer> numMap, List<Long> storeIds, Date time) {
        // 获取当前最大书号
//        Books maxBooks = booksService.getMaxBookNum();

//        List<String> bookNums = new ArrayList<>();

        // 获取书籍分类
        Map<String, Long> bookLabelMap = BooksUtil.getBookLabelMap();

        List<String> isbnList = newList.stream().map(Books::getIsbn).collect(Collectors.toList());
        List<Books> booksList = booksService.getByIsbnAndImgNotNull(isbnList);

        Map<String, List<Books>> booksMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(booksList))
            booksMap = booksList.stream().collect(Collectors.groupingBy(Books::getIsbn));

        for (int i = 0; i < newList.size(); i++) {
            Books books = newList.get(i);
            String isbn = books.getIsbn();
//            try {
//                String bookNum = BooksUtil.getBookNum(maxBooks, i + 1);
//                books.setBookNum(bookNum);
//                bookNums.add(bookNum);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

            List<Books> bookDtoList = booksMap.get(books.getIsbn());
            if (CollectionUtils.isEmpty(bookDtoList)) {
                System.out.println("阿里云查询书籍，isbn：" + isbn);
                AliyunBookDto.ResultDTO aliBookDto = null;
                R<AliyunBookDto.ResultDTO> r = AliyunBookUtil.getBook(isbn);
                if (R.isError(r)) {
                    System.out.println(r.getMsg());
                } else {
                    aliBookDto = r.getData();
                    if (null != aliBookDto) {
                        books.setImg(aliBookDto.getPic());
                        if (null == books.getUnitPrice())
                            books.setUnitPrice(AliyunBookUtil.getPrice(aliBookDto.getPrice()));
                        if (StringUtils.isBlank(books.getAuthor()))
                            books.setAuthor(aliBookDto.getAuthor());
                        if (StringUtils.isBlank(books.getPress()))
                            books.setPress(aliBookDto.getPublisher());
                        if (StringUtils.isBlank(books.getPubDate()))
                            books.setPubDate(aliBookDto.getPubdate());
                        if (StringUtils.isBlank(books.getSynopsis()))
                            books.setSynopsis(aliBookDto.getSummary());
                    }
                }
            } else {
                Books bookDto = bookDtoList.get(0);
                books.setImg(bookDto.getImg());
                if (null == books.getUnitPrice())
                    books.setUnitPrice(bookDto.getUnitPrice());
                if (StringUtils.isBlank(books.getAuthor()))
                    books.setAuthor(bookDto.getAuthor());
                if (StringUtils.isBlank(books.getPress()))
                    books.setPress(bookDto.getPress());
                if (StringUtils.isBlank(books.getPubDate()))
                    books.setPubDate(bookDto.getPubDate());
                if (StringUtils.isBlank(books.getSynopsis()))
                    books.setSynopsis(bookDto.getSynopsis());
            }

            String labelName = books.getBookLabelName();
            if (StringUtils.isNotBlank(labelName)) {
                Long bookLabelId = bookLabelMap.get(labelName);
                if (null != bookLabelId && bookLabelId > 0) {
                    books.setBookLabelId(bookLabelId);
                    books.setBookLabelName(labelName);
                }
            }
        }
        System.out.println("保存书籍数量：" + newList.size());

        // 批量保存总部书籍
        booksService.saveBatch(newList);

        // 门店导入书籍
//        if (CollectionUtils.isNotEmpty(storeIds)) {
//            List<Books> booksList = booksService.getByBookNums(bookNums);
//            if (CollectionUtils.isNotEmpty(booksList)) {
//                for (Long storeId : storeIds) {
//                    List<StoreBooks> newStoreBookList = new ArrayList<>();
//                    for (Books books : booksList) {
//                        StoreBooks storeBook = new StoreBooks();
//                        storeBook.setStoreId(storeId);
//                        storeBook.setBooksId(books.getId());
//                        storeBook.setBookNum(books.getBookNum());
//                        storeBook.setBookLabelId(books.getBookLabelId());
//                        storeBook.setBookLabelName(books.getBookLabelName());
//                        storeBook.setBookName(books.getBookName());
//                        storeBook.setIsbn(books.getIsbn());
//                        storeBook.setImg(books.getImg());
//                        storeBook.setAuthor(books.getAuthor());
//                        storeBook.setUnitPrice(books.getUnitPrice());
//                        storeBook.setIntroduction(books.getIntroduction());
//                        storeBook.setSynopsis(books.getSynopsis());
//                        storeBook.setPress(books.getPress());
//                        storeBook.setPubDate(books.getPubDate());
//                        Integer num = numMap.get(books.getIsbn());
//                        num = NepUtil.nullToZero(num);
//                        storeBook.setStockCount(num);
//                        storeBook.setBorrowCount(num);
//                        storeBook.setStatus(1);
//                        storeBook.setSource(1);
//                        newStoreBookList.add(storeBook);
//                    }
//                    // 保存门店书籍
//                    storeBooksService.saveBatch(newStoreBookList);
//                }
//            }
//        }
    }

    /**
     * 异步批量插入门店书籍，阿里云查询
     */
    @Async
    public void insertStoreBook(List<StoreBooks> storeBooksList, List<String> isbnList, Integer aliYunSearch, Long storeId) {
        List<Books> booksList = booksService.getByIsbnAndImgNotNull(isbnList);
        Map<String, List<Books>> booksMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(booksList))
            booksMap = booksList.stream().collect(Collectors.groupingBy(Books::getIsbn));

        // 保存门店书籍
        int aliNumOk = 0;
        List<String> aliYunNoIsbn = new ArrayList<>();
        Date time = DateUtil.getNowDatetime();
        List<StoreBooks> newList = new ArrayList<>();

        for (int i = 0; i < storeBooksList.size(); i++) {
            StoreBooks storeBook = storeBooksList.get(i);

            String isbn = storeBook.getIsbn();
            Books books = null;
            List<Books> bookList = booksMap.get(isbn);
            if (CollectionUtils.isNotEmpty(bookList)) {
                books = bookList.get(0);
                storeBook.setSource(1);
            } else if (null != aliYunSearch && aliYunSearch.equals(1)) {
                // 自营门店才能使用阿里云查询
                System.out.println("阿里云查询书籍，isbn：" + isbn);
                R<AliyunBookDto.ResultDTO> r = AliyunBookUtil.getBook(isbn);
                if (R.isError(r)) {
                    aliYunNoIsbn.add(isbn);
                } else {
                    AliyunBookDto.ResultDTO resultDto = r.getData();
                    String bookNum = null;
                    // 获取当前最大书号
//                    Books maxBooks = booksService.getMaxBookNum();
//                    try {
//                        bookNum = BooksUtil.getBookNum(maxBooks);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    // 新增总部系统书籍
                    books = BooksUtil.aliNewBooks(resultDto, storeBook.getIsbn(), bookNum, storeBook.getBookName(),
                            storeBook.getPress(), storeBook.getPubDate(), storeBook.getAuthor(), storeBook.getUnitPrice(),
                            storeBook.getBookLabelId(), storeBook.getBookLabelName(), storeId, time);
                    booksService.saveOrUpdate(books);
                    // 阿里云查询次数+1
                    aliNumOk++;
                    storeBook.setSource(2);
                }
            }
            if (null != books) {
                storeBook.setBooksId(books.getId());
                storeBook.setBookNum(books.getBookNum());
                if (StringUtils.isBlank(storeBook.getImg()))
                    storeBook.setImg(books.getImg());
                if (StringUtils.isBlank(storeBook.getSynopsis()))
                    storeBook.setSynopsis(books.getSynopsis());
                if (null == storeBook.getUnitPrice())
                    storeBook.setUnitPrice(books.getUnitPrice());
                if (StringUtils.isBlank(storeBook.getPress()))
                    storeBook.setPress(books.getPress());
                if (StringUtils.isBlank(storeBook.getPubDate()))
                    storeBook.setPubDate(books.getPubDate());
                if (StringUtils.isBlank(storeBook.getAuthor()))
                    storeBook.setAuthor(books.getAuthor());
                if (null == storeBook.getBookLabelId())
                    storeBook.setBookLabelId(books.getBookLabelId());
                if (StringUtils.isBlank(storeBook.getBookLabelName()))
                    storeBook.setBookLabelName(books.getBookLabelName());
            }
            storeBook.setStatus(1);
            storeBook.setAddTime(time);
            storeBook.setEditTime(time);

            newList.add(storeBook);
        }

        // jdbc批量新增门店书籍
        storeBooksService.saveBatch(newList);

        System.out.println("保存的门店书籍总数：" + newList.size() + "，阿里云查询次数：" + aliNumOk + "，阿里云未查询到的书号：" + aliYunNoIsbn);
    }

    /**
     * 异步批量插入门店书籍，阿里云查询
     */
    @Async
    public void insertStoreBookV2(List<StoreBooks> storeBooksList, List<String> isbnList, Integer aliYunSearch, Long storeId) {
        List<Books> booksList = booksService.getByIsbnAndImgNotNull(isbnList);
        Map<String, List<Books>> booksMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(booksList))
            booksMap = booksList.stream().collect(Collectors.groupingBy(Books::getIsbn));

        // 保存门店书籍
        int aliNumOk = 0;
        List<String> aliYunNoIsbn = new ArrayList<>();
        Date time = DateUtil.getNowDatetime();
        List<StoreBooks> newList = new ArrayList<>();

        for (int i = 0; i < storeBooksList.size(); i++) {
            StoreBooks storeBook = storeBooksList.get(i);

            String isbn = storeBook.getIsbn();
            Books books = null;
            List<Books> bookList = booksMap.get(isbn);
            if (CollectionUtils.isNotEmpty(bookList)) {
                books = bookList.get(0);
                storeBook.setSource(1);
            } else if (null != aliYunSearch && aliYunSearch.equals(1)) {
                if (isbn.startsWith("9787")) {
                    // 自营门店才能使用阿里云查询
                    System.out.println("阿里云查询书籍，isbn：" + isbn);
                    R<AliyunBookDto.ResultDTO> r = AliyunBookUtil.getBook(isbn);
                    if (R.isError(r)) {
                        aliYunNoIsbn.add(isbn);
                    } else {
                        AliyunBookDto.ResultDTO resultDto = r.getData();
                        String bookNum = null;
                        // 新增总部系统书籍
                        books = BooksUtil.aliNewBooks(resultDto, storeBook.getIsbn(), bookNum, storeBook.getBookName(),
                                storeBook.getPress(), storeBook.getPubDate(), storeBook.getAuthor(), storeBook.getUnitPrice(),
                                storeBook.getBookLabelId(), storeBook.getBookLabelName(), storeId, time);
                        booksService.saveOrUpdate(books);
                        // 阿里云查询次数+1
                        aliNumOk++;
                        storeBook.setSource(2);
                    }
                }
            }
            if (null != books) {
                storeBook.setBooksId(books.getId());
                storeBook.setBookNum(books.getBookNum());

                if (StringUtils.isBlank(storeBook.getBookName()))
                    storeBook.setBookName(books.getBookName());
                if (StringUtils.isBlank(storeBook.getImg()))
                    storeBook.setImg(books.getImg());
                if (StringUtils.isBlank(storeBook.getSynopsis()))
                    storeBook.setSynopsis(books.getSynopsis());
                if (null == storeBook.getUnitPrice())
                    storeBook.setUnitPrice(books.getUnitPrice());
                if (StringUtils.isBlank(storeBook.getPress()))
                    storeBook.setPress(books.getPress());
                if (StringUtils.isBlank(storeBook.getPubDate()))
                    storeBook.setPubDate(books.getPubDate());
                if (StringUtils.isBlank(storeBook.getAuthor()))
                    storeBook.setAuthor(books.getAuthor());
                if (null == storeBook.getBookLabelId())
                    storeBook.setBookLabelId(books.getBookLabelId());
                if (StringUtils.isBlank(storeBook.getBookLabelName()))
                    storeBook.setBookLabelName(books.getBookLabelName());
            }
            storeBook.setStatus(1);
            storeBook.setAddTime(time);
            storeBook.setEditTime(time);

            newList.add(storeBook);
        }

        // jdbc批量新增门店书籍
        storeBooksService.saveBatch(newList);

        System.out.println("保存的门店书籍总数：" + newList.size() + "，阿里云查询次数：" + aliNumOk + "，阿里云未查询到的书号：" + aliYunNoIsbn);
    }

}
